package com.l024.user.controller;

import com.l024.common.utils.LogUtils;
import com.l024.config.config.utils.JwtUtil;
import com.l024.model.result.R;
import com.l024.model.user.MeetUser;
import com.l024.user.shiro.JwtToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class LoginController {

    @GetMapping("/login")
    public R login(MeetUser user) {
        if (StringUtils.isEmpty(user.getUPhone()) || StringUtils.isEmpty(user.getUPassword())) {
            return R.error(500,"请输入用户名和密码！");
        }
        //用户认证信息
        Subject subject = SecurityUtils.getSubject();
        JwtUtil jwtUtil = new JwtUtil();
        Map<String, Object> chaim = new HashMap<>();
        chaim.put("username", user.getUPhone());
        chaim.put("password", user.getUPassword());
        String token = jwtUtil.encode(user.getUPhone(), 5 * 60 * 1000, chaim);
        JwtToken jwtToken = new JwtToken(token);
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(
                user.getUPhone(),
                user.getUPassword()
        );

        try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(jwtToken);
//            subject.checkRole("admin");
//            subject.checkPermissions("query", "add");
        } catch (UnknownAccountException e) {
            LogUtils.logInfo("用户名不存在！");
            return R.error(500,"用户名不存在！");
        } catch (AuthenticationException e) {
            LogUtils.logInfo("账号或密码错误！");
            return R.error(500,"账号或密码错误！");
        } catch (AuthorizationException e) {
            LogUtils.logInfo("没有权限！");
            return R.error(401,"没有权限！");
        }
        MeetUser meetUser = (MeetUser) SecurityUtils.getSubject().getPrincipal();
        meetUser.setToken(token);
        return R.ok("登录成功",meetUser);
    }

    @RequiresRoles("admin")
    @GetMapping("/admin")
    public String admin() {
        return "admin success!";
    }

//    @RequiresPermissions("guest")
    @GetMapping("/index")
    public String index() {
        return "index success!";
    }

//    @RequiresPermissions("guest")
    @GetMapping("/add")
    public String add() {
        return "add success!";
    }
}
